#include "time_utils.h"
#include "stm32f1xx_hal.h"
#include "rtthread.h"

// 延时（毫秒）
void delayMillisecond(uint32_t ms)
{
    uint32_t t0 = micros();
    while (micros() - t0 < ms * 1000)
        __NOP();
}

// 延时（微秒）
void delayMicroseconds(uint32_t us)
{
    uint32_t t0 = micros();
    while (micros() - t0 < us)
        __NOP();
}

// 用于检查滴答定时器是否激活
__STATIC_INLINE uint32_t LL_SYSTICK_IsActiveCounterFlag()
{
    return ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == (SysTick_CTRL_COUNTFLAG_Msk));
}

// 获取系统启动以来的微秒数
uint64_t micros()
{
    /* Ensure COUNTFLAG is reset by reading SysTick control and status register */
    LL_SYSTICK_IsActiveCounterFlag();

//    uint32_t m = HAL_GetTick(); // HAL库实现
    uint32_t m = rt_tick_get(); // 获取系统节拍数，默认就是1000个/s

    static const uint32_t tms = SysTick->LOAD + 1;
    __IO uint32_t u = tms - SysTick->VAL;

    if (LL_SYSTICK_IsActiveCounterFlag())
    {
        m = rt_tick_get();
        u = tms - SysTick->VAL;
    }

    return (m * 1000 + (u * 1000) / tms);
}
